var app = getApp()
var http = app.require('utils/http.js')
var util = app.require('utils/util.js')
var validator = require('../../../utils/validator.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        model: '',
        detail: {},
        showArea: false,
        areas: [],
        areaTreeFieldNames: {
            text: 'name',
            value: 'id',
            children: 'children',
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        let id = options.id || ''
        if (id != '') {
            http.request('customer/read', {id: id}, function(res) {
                that.setData({
                    detail: res
                })

                http.request('area/readAreaTreeById', {id: res.areaId}, function(res2) {
                    that.setData({
                        areas: res2
                    })
                })
            })
        } else {
            http.request('area/readByPid', {pid: '0'}, function(res) {
                that.setData({
                    areas: res
                })
            })
        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    bindInput(e) {
        let dataset = e.currentTarget.dataset;
        let value = e.detail.value;
        if (!value) {
            value = e.detail
        }
        let index = dataset.index;
        if (index != undefined) {
          this.data[dataset.obj][index][dataset.item] = value;
          this.setData({
            [dataset.obj]: this.data[dataset.obj]
          })
        } else {
          this.data[dataset.obj][dataset.item] = value;
          this.setData({
            [dataset.obj]: this.data[dataset.obj]
          })
        }
    },

    showAreaCascader() {
        this.setData({
            showArea: true,
        });
    },

    hideAreaCascader() {
        this.setData({
            showArea: false,
        });
    },

    handlerChangeArea(e) {
        let that = this
        const { selectedOptions, value } = e.detail;
        let tmpAreas = that.data.areas
        let selectedOptionsCount = selectedOptions.length
        let requestMethod = selectedOptionsCount == 2 ? "area/readByPidExcludeChildren" : "area/readByPid"
        http.request(requestMethod, {pid: value}, function(res) {
            for (let i = 0; i < tmpAreas.length; ++i) {
                let province = tmpAreas[i];
                if (province.id != selectedOptions[0].id) {
                    continue
                }

                if (province.id == value) {
                    province['children'] = res
                    that.setData({
                        areas: tmpAreas
                    })
                } else {
                    let citys = province.children
                    for (let j = 0; j < citys.length; ++j) {
                        let city = citys[j]
                        if (city.id != selectedOptions[1].id) {
                            continue
                        }

                        if (city.id == value) {
                            city['children'] = res
                            that.setData({
                                areas: that.data.areas
                            })
                        }
                    }
                }
            }
        })
    },

    doSelectArea(e) {
        let that = this
        const { selectedOptions, value } = e.detail;
        const fieldValue = selectedOptions
            .map((option) => option.text || option.name)
            .join('/');
        that.data.detail['areaId'] = value
        that.data.detail['areaInfo'] = fieldValue
        this.setData({
            detail:  that.data.detail,
            showArea: false,
        })
    },

    submit() {
        let that = this
        if (validator.isEmptyObj(that.data.detail.name)) {
            util.toast('请输入客户名称', 'none', 2000)
            return
        }
        if (validator.isEmptyObj(that.data.detail.linkman)) {
            util.toast('请输入联系人', 'none', 2000)
            return
        }
        if (validator.isEmptyObj(that.data.detail.linkPhone)) {
            util.toast('请输入联系电话', 'none', 2000)
            return
        }
        
        let requestParams = that.data.detail
        http.request('customer/save', requestParams, function(res) {
            util.toast('保存成功', 'success', 2000, function() {
                that.refreshPrePage(that.data.detail.id ? 'update' : 'create');
                wx.navigateBack();
            })
        })
    },

    refreshPrePage(optionType) {
        let pages = getCurrentPages();
        if (pages.length > 1) {
          let prePage = pages[pages.length - 2];
            prePage.reloadAllListDatas();
        }
      },
})